
<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="title"
    :visible.sync="show"
    width="1000px"
    center
  >
    <el-form ref="form" :rules="rules" style="padding-top: 10px;" :model="form" label-width="100px">
      <div class="com-form-title">标识信息</div>
      <el-row>
        <el-col :span="12">
          <el-form-item label="身份" prop="identifyType" label-width="150px">
            <el-select v-model="form.identifyType" :disabled="disableForm" style="width: 100%;" placeholder="请选择">
              <el-option v-for="item in identifyTypes" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode" label-width="150px">
            <el-input v-model="form.unifiedSocialCreditCode" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号" prop="identifyNumber" label-width="150px">
            <el-input v-model="form.identifyNumber" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <a class="code" href="https://www.qixin.com/">统一社会信用代码查询</a>
        </el-col>
      </el-row>
      <div class="com-form-title">基本信息</div>
      <el-row>
        <el-col :span="12">
          <el-row>
            <el-col :span="12">
              <el-form-item label="编号" prop="number">
                <el-input v-model="form.number" :disabled="disableForm" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" :disabled="disableForm" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="省份" prop="province">
                <el-select v-model="form.province" :disabled="disableForm" style="width: 100%;" placeholder="请选择省份" @change="provinceChange">
                  <el-option v-for="item in provinceData" :key="item.name" :label="item.name" :value="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="城市" prop="city">
                <el-select v-model="form.city" :disabled="disableForm" style="width: 100%;" placeholder="请选择城市">
                  <el-option v-for="item in cityData" :key="item.name" :label="item.name" :value="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="机构等级" prop="organizationLevel">
            <el-select v-model="form.organizationLevel" :disabled="disableForm" style="width: 100%;" placeholder="请选择">
              <el-option v-for="item in organizationLevels" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="简介" prop="description">
            <el-input v-model="form.description" :disabled="disableForm" type="textarea" />
          </el-form-item>
          <el-form-item label="纳税规模" prop="city">
            <el-select v-model="form.taxScale" :disabled="disableForm" style="width: 100%;" placeholder="请选择纳税规模">
              <el-option label="一般纳税人" value="1" />
              <el-option label="小规模纳税人" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-row>
            <el-col :span="12">
              <el-form-item label="法人代表" prop="legalPerson">
                <el-input v-model="form.legalPerson" :disabled="disableForm" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="注册资金" prop="registeredCapital">
                <el-input v-model="form.registeredCapital" :disabled="disableForm" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="地址" prop="address">
            <el-input v-model="form.address" :disabled="disableForm" />
          </el-form-item>
          <el-form-item :label="typeLabel" prop="supplierCategoryIds">
            <el-cascader
              v-model="form.supplierCategoryIds"
              style="width: 100%;"
              placeholder="请选择"
              :options="options"
              :props="props"
              collapse-tags
              clearable
              filterable
            />

          </el-form-item>
          <el-form-item label="经营范围" prop="businessScope">
            <el-input v-model="form.businessScope" :disabled="disableForm" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="com-form-title">扩展信息</div>
      <el-row>
        <el-col :span="12">
          <el-row>
            <el-col :span="12">
              <el-form-item label="联系人姓名" prop="contactName">
                <el-input v-model="form.contactName" :disabled="disableForm" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系人手机" prop="contactPhone">
                <el-input v-model="form.contactPhone" :disabled="disableForm" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="固话" prop="fixed">
                <el-input v-model="form.fixed" :disabled="disableForm" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮编" prop="postCode">
                <el-input v-model="form.postCode" :disabled="disableForm" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" :disabled="disableForm" />
          </el-form-item> -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" :disabled="disableForm" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="传真" prop="fax">
                <el-input v-model="form.fax" :disabled="disableForm" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="通讯地址" prop="contactAddress">
            <el-input v-model="form.contactAddress" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!-- <el-row>
            <el-col :span="12">
            </el-col>
          </el-row> -->
          <el-form-item label="评定级别" prop="rating">
            <el-select v-model="form.rating" :disabled="disableForm" style="width: 100%;" placeholder="请选择">
              <el-option v-for="item in ratingLevels" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="type === '2'" label="开户行" prop="accountBank">
            <el-input v-model="form.accountBank" :disabled="disableForm" />
          </el-form-item>
          <el-form-item v-if="type === '2'" label="银行账号" prop="bankAccount">
            <el-input v-model="form.bankAccount" :disabled="disableForm" />
          </el-form-item>
          <template v-if="type === '1' || type === '4'">
            <el-form-item label="安全许可证" prop="securityLicense">
              <el-input v-model="form.securityLicense" :disabled="disableForm" />
            </el-form-item>
            <el-form-item label="资质证书号" prop="qualificationCertificateNumber">
              <el-input v-model="form.qualificationCertificateNumber" :disabled="disableForm" />
            </el-form-item>
            <el-form-item label="资质证等级" prop="qualificationLevel">
              <el-input v-model="form.qualificationLevel" :disabled="disableForm" />
            </el-form-item>
          </template>
          <el-form-item v-if="type === '3'" label="主营产品" prop="product">
            <el-input v-model="form.product" :disabled="disableForm" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="">
        <!-- :auto-upload="false" -->
        <div style="display: flex;align-items: center;">
          <el-button style="margin-right:10px;margin-top:2px;" size="small" type="primary" @click="showTreeModal = true">{{ typeLabel }}</el-button>
          <!-- <uploader v-model="fileList" :disabled="disableForm" :can-download="optType==='detail'" /> -->
          <!-- <div class="com-form-title">附件</div> -->
          <el-button type="primary" @click="showFileModal = true">附件资料({{ fileList.length }})</el-button>
          <file-uploader v-model="fileList" :show-modal.sync="showFileModal" :disabled="disableForm" :can-download="optType==='detail'" />
        </div>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="saveSupplier">确 定</el-button>
    </span>
    <supplier-tree :title="typeLabel" :type="type" :show-modal.sync="showTreeModal" @freshTree="getTreeList" />
  </el-dialog>
</template>

<script>
import { addSupplierInfo, updateSupplierInfo, getSupplierInfoDetail, getSupplierCategoryTree } from '@/api/travellingTraderManage'
import { getAreaList } from '@/api/common'
import { identifyTypes, organizationLevels, ratingLevels } from '@/utils/dicData'
import supplierTree from './supplierTree.vue'
import fileUploader from '@/components/FileUploader'
export default {
  name: 'DirManage',
  components: {
    fileUploader,
    supplierTree
  },
  props: {
    title: {
      type: String,
      default: ''
    },
    typeLabel: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: ''
    },
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      props: {
        label: 'name',
        children: 'nodes',
        multiple: true,
        value: 'id'
      },
      options: [],
      showFileModal: false,
      showTreeModal: false,
      ratingLevels,
      identifyTypes,
      organizationLevels,
      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        identifyType: '',
        unifiedSocialCreditCode: '',
        identifyNumber: '',
        name: '',
        number: '',
        province: '',
        city: '',
        organizationLevel: '',
        description: '',
        legalPerson: '',
        registeredCapital: '',
        address: '',
        supplierCategoryIds: [],
        businessScope: '',
        contactName: '',
        contactPhone: '',
        fixed: '',
        postCode: '',
        email: '',
        fax: '',
        contactAddress: '',
        rating: '',
        taxScale: '1'
        // accountBank: '',
        // bankAccount: '',
        // securityLicense: '',
        // qualificationCertificateNumber: '',
        // qualificationLevel: '',
        // product: ''
      },
      fileList: [
      ],
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'change' }
        ],
        identifyType: [
          { required: true, message: '请选择身份', trigger: 'change' }
        ]
        // unifiedSocialCreditCode: [
        //   { required: true, message: '统一社会信用代码', trigger: 'change' }
        // ]
      },
      provinceData: [],
      cityData: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    showModal(val) {
      if (val && this.optType !== 'add') {
        this.getDocDetail(this.data.id)
        this.$nextTick(() => {
          Object.keys(this.form).forEach(key => {
            if (key === 'supplierCategoryIds') {
              const val = this.data[key]
              if (val) {
                this.form[key] = val.split(',').map(item => [item])
              }
            } else {
              this.form[key] = this.data[key]
            }
          })
        })
      } else if (!val) {
        this.fileList = []
        this.$refs.form.resetFields()
      }
    }
  },
  mounted() {
    this.getRegionData()
    this.getTreeList()
  },
  methods: {
    clearChildren(data) {
      data.map(val => {
        if (!val.nodes.length) {
          val.nodes = null
        } else {
          this.clearChildren(val.nodes)
        }
      })
      return data
    },
    getTreeList() {
      getSupplierCategoryTree({ supplierCategoryType: this.type }).then(res => {
        if (res.data.nodes) {
          this.options = this.clearChildren(res.data.nodes)
        }
      })
    },
    provinceChange(e) {
      const selectedData = this.provinceData.filter(val => val.name === e)[0]
      if (selectedData) {
        this.form.city = ''
        const params = {
          parentCode: selectedData.code,
          areaType: 2
        }
        getAreaList(params).then(res => {
          this.cityData = res.data || []
        })
      }
    },
    getDocDetail(id) {
      getSupplierInfoDetail({ supplierInfoId: id }).then(res => {
        const { lstAttachment } = res.data || {}
        if (lstAttachment && lstAttachment.length > 0) {
          this.fileList = lstAttachment
        }
      })
    },
    getRegionData() {
      getAreaList({ areaType: '1' }).then(res => {
        this.provinceData = res.data || []
      })
    },
    flatten(arr) {
      const str = JSON.stringify(arr).replace(/\[|\]/g, '')
      return JSON.parse(Array.of('[' + str + ']')[0])
    },

    saveSupplier() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const formData = JSON.parse(JSON.stringify(
            this.form
          ))
          if (formData.supplierCategoryIds.length > 0) {
            formData.supplierCategoryIds = this.flatten(formData.supplierCategoryIds).join(',')
          }
          this.form.supplierCategoryIds = formData.supplierCategoryIds
          const params = {
            supplierInfo: {
              ...this.form,
              ...this.optType === 'edit' ? {
                id: this.data.id
              } : {},
              type: this.type
            },
            lstAttachment: this.fileList
          }
          const fn = this.optType === 'add' ? addSupplierInfo : updateSupplierInfo
          fn(params).then(res => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title{
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409EFF;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}

.code{
  margin-left: 30px;
  color: #409EFF;
  padding-top:50px;
}
</style>
